<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Matrix\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 罐箱配件库存
 *
 */
class XStockin extends Backend
{
    /**
     * XStockin模型对象
     * @var \app\admin\model\XStockin
     */
    protected $model = null;
    
    protected $quickSearchField = ['ID'];

    protected $defaultSortField = 'ID,desc';
    protected $noNeedLogin      = ['*'];
    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XStockin;
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $type=$this->request->get('type');
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field("x_stockin.*,DEPARTMENT.DEPTNAME")
            ->join('DEPARTMENT',"x_stockin.DEPT=DEPARTMENT.DEPTID",'left')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 罐箱配件库存查询
     */
    public function index_s()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field("FITTING,STOCKAREA,BRAND,SPECS,PRICE,sum(STOCK) as stock,DEPARTMENT.DEPTNAME,sum(STOCK*PRICE) as prices")
            ->join('DEPARTMENT',"x_stockin.DEPT=DEPARTMENT.DEPTID")
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where('STOCK','>','0')
            ->where($where)
//            ->order($order)
            ->group("FITTING,STOCKAREA,BRAND,SPECS,PRICE,DEPARTMENT.DEPTNAME")
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 配件出库列表
     */
    public function index_c()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field("x_stockin.*,DEPARTMENT.DEPTNAME")
            ->join('DEPARTMENT',"x_stockin.DEPT=DEPARTMENT.DEPTID")
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where('stock','>','0')
            ->where($where)
            ->order($order)

            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['PJIN']='PJIN'. $this->microtime_format('YmdHis',$this->microtime_float());

            $data['OP']=$adminInfo['nickname'];
            $data['DEPT']=isset($data['DEPT'])?$data['DEPT']:$adminInfo['department'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
}